package com.begamer.card.common.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class StringUtil {

	public static SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	public static SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
	public static SimpleDateFormat sdf3 = new SimpleDateFormat("HH:mm:ss");
	public static SimpleDateFormat sdf4 = new SimpleDateFormat("HH:mm");
	public static SimpleDateFormat sdf5 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	public static SimpleDateFormat sdf6 = new SimpleDateFormat("HH");
	public static SimpleDateFormat sdf7 = new SimpleDateFormat("mm");
	public static SimpleDateFormat sdf8 = new SimpleDateFormat("ss");
	public static String getString(String str)
	{
		if (str == null)
			return "";
		return str.trim();
	}

	public static int getInt(String str)
	{
		if (str == null || "".equals(str.trim()))
		{
			return 0;
		}

		try
		{
			return Integer.decode(str.trim());
		}
		catch (Exception e)
		{
			return Integer.valueOf(str.trim());
		}
	}

	public static float getFloat(String str)
	{
		if (str == null || "".equals(str.trim()))
		{
			return 0;
		}
		return Float.valueOf(str.trim());
	}

	/**
	 * gzip压缩 lt@2013-12-16 下午04:48:05
	 * 
	 * @param str
	 * @return
	 * @throws IOException
	 */
	public static String compressByGZIP(String str)
	{
		try
		{
			if (str == null || str.length() == 0)
			{
				return null;
			}
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			GZIPOutputStream gzip = new GZIPOutputStream(out);
			gzip.write(str.getBytes("UTF-8"));
			gzip.finish();
			gzip.flush();
			gzip.close();
			out.close();
			// return out.toString("ISO-8859-1");

			byte[] bytes = out.toByteArray();
			String result = new String(bytes, Charset.forName("ISO-8859-1"));

			// BASE64Encoder tBase64Encoder = new BASE64Encoder();
			// String result=tBase64Encoder.encode(bytes);

			// System.err.println("utf8长度:"+length+",base64后长度:"+result.length()+",长度增加:"+(result.length()-length));

			return result;
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * gzip解压缩 lt@2013-12-16 下午04:46:50
	 * 
	 * @param str
	 * @return
	 * @throws IOException
	 */
	public static String uncompressByGZIP(String str) throws Exception
	{
		if (str == null || str.length() == 0)
		{
			return str;
		}

		// BASE64Decoder tBase64Decoder = new BASE64Decoder ();
		// byte[] bs=tBase64Decoder.decodeBuffer(str);

		byte[] bs = str.getBytes(Charset.forName("ISO-8859-1"));

		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ByteArrayInputStream in = new ByteArrayInputStream(bs);

		GZIPInputStream gunzip = new GZIPInputStream(in);
		byte[] buffer = new byte[256];
		int n;
		while ((n = gunzip.read(buffer)) >= 0)
		{
			out.write(buffer, 0, n);
		}
		gunzip.close();
		in.close();
		out.close();
		// toString()使用平台默认编码，也可以显式的指定如toString("GBK")
		return out.toString("UTF-8");
	}

	public static boolean isToday(String otherDay)
	{
		if (getToday().equals(otherDay))
		{
			return true;
		}
		return false;
	}

	public static boolean isSameDay(long time1, long time2)
	{
		return getDate(time1).equals(getDate(time2));
	}

	public static boolean isSameDay(String dateTime1, String dateTime2)
	{
		if (dateTime1 != dateTime2)
		{
			if ((("".equals(dateTime1) && "".equals(dateTime2)))
					|| ("".equals(dateTime1) && !"".equals(dateTime2))
					|| (!"".equals(dateTime1) && "".equals(dateTime2)))
			{
				return true;
			}
			else
			{
				String d1 = dateTime1.substring(0, 10);
				String d2 = dateTime2.substring(0, 10);
				return d1.equals(d2);
			}
		}
		else
		{
			return true;
		}
	}

	public static boolean isSameMonth(long time1, long time2)
	{
		String date1 = getDate(time1);
		String date2 = getDate(time2);
		return date1.substring(0, 7).equals(date2.substring(0, 7));
	}

	public static String getDate(long time)
	{
		return sdf2.format(time);
	}

	public static String getTime(long time)
	{
		return sdf3.format(time);
	}

	public static String getTime2(long time)
	{
		return sdf4.format(time);
	}

	public static String getDateTime(long time)
	{
		return sdf1.format(time);
	}

	public static String getNow()
	{
		return sdf1.format(System.currentTimeMillis());
	}

	public static String getToday()
	{
		return sdf1.format(System.currentTimeMillis()).substring(0, 10);
	}
	public static String getHours(long time)
	{
		return sdf6.format(time);
	}
	/**
	 * 根据日期时间字串获取时间戳 lt@2014-3-4 下午03:42:49
	 * 
	 * @param dateTime
	 *            yyyy-MM-dd HH:mm:ss
	 * @return
	 */
	public static long getTimeStamp(String dateTime)
	{
		if (dateTime == null || "".equals(dateTime.trim()))
		{
			return 0;
		}
		try
		{
			return sdf1.parse(dateTime).getTime();
		}
		catch (ParseException e)
		{
			e.printStackTrace();
			return 0;
		}
	}

	// public static void main(String[] args)
	// {
	// // System.out.println(getToday());
	// // System.out.println(getTimeStamp("2014-03-04 00:00:00"));
	// //
	// // String src="10101%1-10102%1-10103%0-10104%1";
	// // System.out.println(replaceStr(src, "10103%0", "10103%1"));
	// // System.out.println(replaceStr(src, 5, "&"));
	// //
	// //
	// //
	// // System.out.println(getInt("08"));
	//		
	// // int a=Byte.MIN_VALUE;
	// // int b=Byte.MAX_VALUE;
	// //
	// char max=Character.MAX_VALUE;
	// char min=Character.MIN_VALUE;
	// //
	// // System.out.println("["+(char)(min-1)+"]");
	//		
	//		
	// // char a='a';
	// // char b='b';
	// // System.out.println("a+b="+(a+b));
	// // System.out.println((char)195);
	// // for(int i=min;i<=max;i++)
	// // {
	// // char c=(char)i;
	// // char[] cs=new char[1];
	// // cs[0]=c;
	// // String ss=new String(cs);
	// // System.out.println(i+"["+ss+"]");
	// // System.out.println(i+"=["+(char)i+"]");
	// // byte bt=(byte)i;
	// // byte[] bytes=new byte[1];
	// // bytes[0]=bt;
	// // String s=new String(bytes,Charset.forName("UTF8"));
	// // System.out.println(i+"["+s+"]");
	// // }
	//		
	// System.out.println(getWeekDay(System.currentTimeMillis()));
	//			
	// }

	/** 替换指定位置的字符串* */
	public static String replaceStr(String src, int index, String tar)
	{
		return src.substring(0, index) + "" + tar + ""
				+ src.substring(index + 1, src.length());
	}

	/** 替换字符串* */
	public static String replaceStr(String src, String beReplaced, String tar)
	{
		int index = src.indexOf(beReplaced);
		return src.substring(0, index) + "" + tar + ""
				+ src.substring(index + beReplaced.length(), src.length());
	}

	/** 获取指定位置的字符串* */
	public static String getStr(String src, int index)
	{
		return String.valueOf(src.charAt(index));
	}

	/** 根据当前日期获取周几* */
	public static int getWeekDay(long time)
	{
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(time);
		int num = calendar.get(Calendar.DAY_OF_WEEK);
		if (num == Calendar.SUNDAY)
		{
			return 7;
		}
		else if (num == Calendar.MONDAY)
		{
			return 1;
		}
		else if (num == Calendar.TUESDAY)
		{
			return 2;
		}
		else if (num == Calendar.WEDNESDAY)
		{
			return 3;
		}
		else if (num == Calendar.THURSDAY)
		{
			return 4;
		}
		else if (num == Calendar.FRIDAY)
		{
			return 5;
		}
		else
		{ 
			return 6;
		}
	}

	/** 现在到下个整点的分钟差* */
	public static int getMin(long time)
	{
		String minStr = getNow().substring(14, 16);
		return 60 - StringUtil.getInt(minStr);
	}
	/** 俩个时间差多少秒* */
	public static int getSubSecond(long time1,long time2)
	{
		long time = time2 - time1;
		return StringUtil.getInt(sdf7.format(time))*60+StringUtil.getInt(sdf8.format(time));
	}
	/** 现在到零点的时间差* */
	public static int getHour(long time)
	{
		String houtStr = getNow().substring(11, 13);
		int hour = StringUtil.getInt(houtStr);
		if (24 - hour <= 1)// 如果剩余一小时以内则以分钟计
		{
			return getMin(time);
		}
		return 60 * (24 - hour);
	}

	/** 结束时间与今天之间的时间差* */
	public static int getdays(String time)
	{
		if (getToday().equals(time))// 如果同一天则以小时计
		{
			return getHour(System.currentTimeMillis());
		}
		else
		{
			int day = StringUtil.getInt(time.substring(8, 10))
					- StringUtil.getInt(getNow().substring(8, 10));
			return 24 * day * 60;
		}
	}

	// 对比两天时间，之前，之后
	public static boolean compareTime(String time1, String time2)
	{
		Date date1 = null;
		Date date2 = null;
		Date now = null;
		try
		{
			if (time1 != null && time1.length() > 0)
			{
				date1 = sdf2.parse(time1);
			}
			if (time2 != null && time2.length() > 0)
			{
				date2 = sdf2.parse(time2);
			}

			now = sdf2.parse(getDate(System.currentTimeMillis()));
		}
		catch (Exception e)
		{
			System.out.println("日期转换错误" + e.getMessage());
		}
		if (date1 != null && date2 != null && now != null)
		{
			if (date1.before(now) && date2.after(now))
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		return false;
	}

	/**
	 * 获取本月的天数 lt@2014-4-15 下午08:00:05
	 * 
	 * @return
	 */
	public static int getDayNumsOfThisMonth()
	{
		String nowDate = getDate(System.currentTimeMillis());
		String[] ss = nowDate.split("-");
		int year = getInt(ss[0]);
		int month = getInt(ss[1]);

		int dayNums = 0;
		if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8
				|| month == 10 || month == 12)
		{
			dayNums = 31;
		}
		else if (month == 2)
		{
			// 闰月
			if ((year % 100 == 0 && year % 400 == 0)
					|| (year % 100 != 0 && year % 4 == 0))
			{
				dayNums = 29;
			}
			else
			{
				dayNums = 28;
			}
		}
		else
		{
			dayNums = 30;
		}
		return dayNums;
	}

	public static String getMailDataTime(long time)
	{
		return sdf5.format(time);
	}

	public static void main(String[] args)
	{
		String date = ofterDayDate("2014-04-21", 7);
		System.out.println(date);
		System.out.println(compareTo("2014-04-21", "2014-05-2"));
	}

	/**
	 * 计算x天后的日期
	 * 
	 * @param date
	 * @param x
	 * @return
	 */
	public static String ofterDayDate(String date, int x)
	{
		String[] dateStrings = date.split("-");
		int year = Integer.parseInt(dateStrings[0]);
		int month = Integer.parseInt(dateStrings[1]);
		int day = Integer.parseInt(dateStrings[2]) + x;

		if (day > 30 && (month == 4 || month == 6 || month == 9 || month == 11))
		{
			day = day - 30;
			if (month == 12)
			{
				month = 1;
				year = year + 1;
			}
			else
			{
				month = month + 1;
			}
		}
		else if (day > 31
				&& (month == 1 || month == 3 || month == 5 || month == 7
						|| month == 8 || month == 10 || month == 12))
		{
			day = day - 31;
			if (month == 12)
			{
				month = 1;
				year = year + 1;
			}
			else
			{
				month = month + 1;
			}
		}
		else if (month == 2)
		{
			if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
			{
				if (day > 29)
				{
					day = day - 29;
					month = 3;
				}
			}
			else
			{
				if (day > 28)
				{
					day = day - 28;
					month = 3;
				}
			}
		}

		String y = year + "-";
		String m = "";
		String d = "";
		if (month < 10)
		{
			m = "0" + month + "-";
		}
		else
		{
			m = month + "-";
		}
		if (day < 10)
		{
			d = "0" + day;
		}
		else
		{
			d = day + "";
		}
		return y + m + d;
	}
	
	/***
	 * 2个日期相差几天
	 * @param day1
	 * @param day2
	 * @return
	 */
	public static int compareTo(String day1,String day2)
	{
		int day = 0;
		try
		{
			Calendar cal1=Calendar.getInstance();
			cal1.setTime(sdf2.parse(day1));
			Calendar cal2=Calendar.getInstance();
			cal2.setTime(sdf2.parse(day2));
			long l=cal2.getTimeInMillis()-cal1.getTimeInMillis();
			day=new Long(l/(1000*60*60*24)).intValue();
			
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return day;
	}

	/**
	 * 匹配非中英文数字下划线
	 * lt@2014-7-7 下午02:45:11
	 * @param s
	 * @return
	 */
	public static boolean match(String s)
	{
		String regex = "[^\u4e00-\u9fa5\\w]";
		Pattern p=Pattern.compile(regex);
		Matcher matcher=p.matcher(s);
		return matcher.find();
	}
	
}
